//
//  MultiTouchExampleViewController.m
//  MultiTouchExample
//

#import "MultiTouchExampleViewController.h"

@implementation MultiTouchExampleViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	
	float boxSize = 100.0;
	CGRect redBoxRect = CGRectMake(110,180,boxSize,boxSize);
	redBox = [[UIView alloc] initWithFrame:redBoxRect];
	redBox.backgroundColor = [UIColor redColor];
	redBox.multipleTouchEnabled = YES;
	
	[self.view addSubview:redBox];
}

CGFloat distanceBetweenPoints(CGPoint pt1, CGPoint pt2) {
	CGFloat distance;
	
	CGFloat xDifferenceSquared = pow(pt1.x - pt2.x, 2);
	CGFloat yDifferenceSquared = pow(pt1.y - pt2.y, 2);
	distance = sqrt(xDifferenceSquared + yDifferenceSquared);
	
	return distance;
}

CGAffineTransform transformWithScale(CGAffineTransform oldTransform,
									 UITouch *touch1,
									 UITouch *touch2) {
	CGPoint touch1Location = [touch1 locationInView:nil];
	CGPoint touch1PreviousLocation = [touch1 previousLocationInView:nil];
	CGPoint touch2Location = [touch2 locationInView:nil];
	CGPoint touch2PreviousLocation = [touch2 previousLocationInView:nil];
	
	// 점 사이의 거리를 구한다
	CGFloat distance = distanceBetweenPoints(touch1Location, touch2Location);
	CGFloat prevDistance = distanceBetweenPoints(touch1PreviousLocation,
												 touch2PreviousLocation);
	
	// 확대/축소 비율 계산
	CGFloat scaleRatio = distance / prevDistance;
	
	CGAffineTransform newTransform = CGAffineTransformScale(oldTransform,
															scaleRatio,
															scaleRatio);
	
	//
	return newTransform;
}

CGAffineTransform transformWithRotation(CGAffineTransform oldTransform,
										UITouch *touch,
										UIView *view,
										id superview) {
	CGPoint pt1 = [touch locationInView:superview];
	CGPoint pt2 = [touch previousLocationInView:superview];
	CGPoint center = view.center;
	CGFloat angle1 = atan2(center.y - pt2.y, center.x - pt2.x);
	CGFloat angle2 = atan2(center.y - pt1.y, center.x - pt1.x);
	
	CGAffineTransform newTransform = CGAffineTransformRotate(oldTransform, angle2-angle1);
	
	//
	return newTransform;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	if ([[event touchesForView:redBox] count] == 1) {
		UITouch *touch = [[[event touchesForView:redBox] allObjects] objectAtIndex:0];
		redBox.transform = transformWithRotation(redBox.transform, touch, redBox, self.view);
	}
	if ([[event touchesForView:redBox] count] == 2) {
		UITouch *touch1 = [[[event touchesForView:redBox] allObjects] objectAtIndex:0];
		UITouch *touch2 = [[[event touchesForView:redBox] allObjects] objectAtIndex:1];
		redBox.transform = transformWithScale(redBox.transform, touch1, touch2);
	}
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	for (UITouch *touch in [event touchesForView:redBox])
		NSLog(@"touch at location: %@",
			  NSStringFromCGPoint([touch locationInView:self.view]));
}

- (void)dealloc {
	[redBox release];
    [super dealloc];
}

@end
